<template>
    <ul ref="appMenuRef" class="d-contextmenu d-contextmenu-animation" v-if="showMenu"
        :style="{ left: menuLeft + 'px', top: menuTop + 'px' }">
        <slot name="li"></slot>
    </ul>
</template>

<script setup lang="ts">
//右键菜单 宽度140px
const menuLeft = ref(0)
const menuTop = ref(0)
const showMenu = ref(false)
const appMainRef = ref<Element>()
const appMenuRef = ref<HTMLUListElement>()
const showAppMainMenu = (e: MouseEvent) => {
    showMenu.value = false
    nextTick(() => {
        showMenu.value = true
        menuLeft.value = e.clientX
        menuTop.value = e.clientY
        //处理右侧宽度不够
        if (appMainRef.value!.clientWidth - menuLeft.value < 140)
            menuLeft.value = menuLeft.value - 140
        document.addEventListener('click',close)
    })
}

const close = () => {
    if(showMenu.value){
        showMenu.value = false
        document.removeEventListener('click',close)
    }
}

//处理下边宽度不够
watchEffect(() => {
    if (showMenu.value) {
        nextTick(() => {
            if (appMenuRef.value?.clientHeight && appMenuRef.value?.clientHeight + menuTop.value > appMainRef.value!.clientHeight) {
                menuTop.value = appMainRef.value!.clientHeight - appMenuRef.value?.clientHeight
            }
        })
    }
})

onMounted(() => {
    appMainRef.value = document.getElementsByClassName('app-main')[0]
})

defineExpose({
    showAppMainMenu,
    close
})
</script>

<style scoped></style>